import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/moment.dart';
import '../services/moment_service.dart';
import '../utils/date_formatter.dart';
import 'create_moment_page.dart';

class MomentDetailPage extends StatefulWidget {
  final Moment moment;

  const MomentDetailPage({
    super.key,
    required this.moment,
  });

  @override
  State<MomentDetailPage> createState() => _MomentDetailPageState();
}

class _MomentDetailPageState extends State<MomentDetailPage> {
  late final MomentService _momentService;
  late Moment _currentMoment;
  bool _isLoadingDetail = true;

  @override
  void initState() {
    super.initState();
    // 初始化当前Moment为传入的列表数据
    _currentMoment = widget.moment;

    // 初始化MomentService，传入401回调
    _momentService = MomentService(
      onUnauthorized: _handleUnauthorized,
    );

    // 异步加载完整详情
    _loadMomentDetail();
  }

  // 加载完整的Moment详情
  Future<void> _loadMomentDetail() async {
    try {
      final detailMoment = await _momentService.getMomentDetail(widget.moment.id);
      if (mounted) {
        setState(() {
          _currentMoment = detailMoment;
          _isLoadingDetail = false;
        });
      }
    } catch (e) {
      // 如果加载详情失败，仍然使用列表数据，只是不显示加载状态
      if (mounted) {
        setState(() {
          _isLoadingDetail = false;
        });
      }
    }
  }

  // 处理401未授权，跳转到登录页
  void _handleUnauthorized() {
    Navigator.of(context).pushReplacementNamed('/login');
  }

  Future<void> _navigateToEdit(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CreateMomentPage(moment: _currentMoment),
      ),
    );

    // 如果编辑成功，返回更新后的 Moment 对象
    if (result != null && result is Moment && context.mounted) {
      // 关闭当前详情页并替换为新的详情页
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => MomentDetailPage(moment: result),
        ),
      );
    }
  }

  void _handleLinkTap(String text, String? href, String title) async {
    if (href == null) return;

    final uri = Uri.tryParse(href);
    if (uri != null && await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    }
  }

  String _processHashtags(String content) {
    // 将 hashtag 转换为行内代码格式，这样可以通过 code 样式高亮显示
    // 匹配所有 #标签 格式（#后面直接跟非空白字符，没有空格）
    // Markdown的标题需要 "# 空格"，所以 #标签 不会被误判为标题
    return content.replaceAllMapped(
      RegExp(r'#([^\s#`]+)'),
      (match) => '`#${match.group(1)}`',
    );
  }

  Widget _buildMarkdownContent(String content) {
    // 预处理内容，转换 hashtag
    final processedContent = _processHashtags(content);

    return MarkdownBody(
      data: processedContent,
      selectable: true,
      onTapLink: _handleLinkTap,
      styleSheet: MarkdownStyleSheet(
        // 段落样式
        p: const TextStyle(
          fontSize: 14,
          color: Color(0xFF353535),
          height: 1.75,
          letterSpacing: 0.8,
        ),
        // 链接样式
        a: const TextStyle(
          color: Color(0xFF37352F),
          decoration: TextDecoration.underline,
          decorationColor: Color(0x6637352F),
        ),
        // 粗体样式 - 带黄色背景
        strong: const TextStyle(
          fontWeight: FontWeight.bold,
          backgroundColor: Color(0xFFFFF3E0),
        ),
        // 斜体样式 - 红色
        em: const TextStyle(
          fontStyle: FontStyle.italic,
          color: Color(0xFFF83929),
        ),
        // 标题样式
        h1: const TextStyle(
          fontSize: 22,
          fontWeight: FontWeight.w300,
          color: Color(0xFF353535),
        ),
        h2: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w700,
          color: Color(0xFF353535),
        ),
        h3: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w600,
          color: Color(0xFF353535),
        ),
        h4: const TextStyle(
          fontSize: 15,
          fontWeight: FontWeight.w600,
          color: Color(0xFF353535),
        ),
        h5: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
          color: Color(0xFF353535),
        ),
        h6: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
          color: Color(0xFF353535),
        ),
        // 列表样式
        listBullet: const TextStyle(
          fontSize: 14,
          color: Color(0xFFF83929),
        ),
        // 引用样式
        blockquote: const TextStyle(
          fontSize: 14,
          color: Color(0xFF353535),
          height: 1.75,
        ),
        blockquoteDecoration: BoxDecoration(
          color: const Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(13),
        ),
        blockquotePadding: const EdgeInsets.fromLTRB(10, 10, 10, 25),
        // 代码块样式
        code: const TextStyle(
          fontFamily: 'monospace',
          fontSize: 12,
          color: Color(0xFF383A42),
          backgroundColor: Color(0xFFEEEEEE),
        ),
        codeblockDecoration: BoxDecoration(
          color: const Color(0xB3EEEEEE),
          borderRadius: BorderRadius.circular(5),
        ),
        codeblockPadding: const EdgeInsets.all(16),
        // 行内代码样式
        codeblockAlign: WrapAlignment.start,
        // 表格样式
        tableHead: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
          color: Color(0xFF353535),
        ),
        tableBody: const TextStyle(
          fontSize: 13,
          color: Color(0xFF353535),
        ),
        tableBorder: TableBorder.all(
          color: const Color(0xFFCCCCCC),
          width: 1,
        ),
        tableCellsPadding: const EdgeInsets.symmetric(
          horizontal: 8,
          vertical: 5,
        ),
        // 水平分隔线
        horizontalRuleDecoration: BoxDecoration(
          border: Border(
            top: BorderSide(
              width: 1,
              color: Colors.grey.shade400,
            ),
          ),
        ),
        // 图片边距
        blockSpacing: 10,
        listIndent: 24,
      ),
    );
  }

  Future<void> _deleteMoment(BuildContext context) async {
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这条记录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed != true || !context.mounted) return;

    // 显示加载提示
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    try {
      await _momentService.deleteMoment(_currentMoment.id);

      if (context.mounted) {
        Navigator.pop(context); // 关闭加载提示
        Navigator.pop(context, 'deleted'); // 返回列表页，标记为删除操作
      }
    } catch (e) {
      if (context.mounted) {
        Navigator.pop(context); // 关闭加载提示
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败: $e')),
        );
      }
    }
  }

  Future<void> _toggleFavorite(BuildContext context) async {
    // 显示加载提示
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

    try {
      await _momentService.updateFavorite(_currentMoment.id, true);

      if (context.mounted) {
        Navigator.pop(context); // 关闭加载提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('收藏成功')),
        );
        Navigator.pop(context, 'favorited'); // 返回列表页，标记为收藏操作
      }
    } catch (e) {
      if (context.mounted) {
        Navigator.pop(context); // 关闭加载提示
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('收藏失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果 title 不为空，使用 title 作为标题，否则使用默认的 '详情'
    final appBarTitle = _currentMoment.title?.isNotEmpty == true
        ? _currentMoment.title!
        : '详情';

    return Scaffold(
      backgroundColor: const Color(0xFFFFFFFF),
      appBar: AppBar(
        title: Text(appBarTitle),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          PopupMenuButton<String>(
            onSelected: (value) {
              if (value == 'edit') {
                _navigateToEdit(context);
              } else if (value == 'delete') {
                _deleteMoment(context);
              } else if (value == 'favorite') {
                _toggleFavorite(context);
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'edit',
                child: Row(
                  children: [
                    Icon(Icons.edit, size: 20),
                    SizedBox(width: 8),
                    Text('编辑'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'favorite',
                child: Row(
                  children: [
                    Icon(Icons.favorite, size: 20, color: Colors.red),
                    SizedBox(width: 8),
                    Text('收藏'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'delete',
                child: Row(
                  children: [
                    Icon(Icons.delete, size: 20, color: Colors.red),
                    SizedBox(width: 8),
                    Text('删除', style: TextStyle(color: Colors.red)),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  DateFormatter.formatForDetail(_currentMoment.createdTime),
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                if (_currentMoment.isFavorite)
                  const Icon(
                    Icons.favorite,
                    color: Colors.red,
                    size: 16,
                  ),
              ],
            ),
            const SizedBox(height: 16),
            _buildMarkdownContent(_currentMoment.content),
            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }
}
